//
//  ConsigneListVC.m
//  ProjectforHDX
//
//  Created by Jaesun on 16/8/1.
//  Copyright © 2016年 H.DX. All rights reserved.
//

#import "ConsigneeListVC.h"

#import "ConsigneeListCell.h" // 自定义cell
#import "AddConsigneeView.h" // 自定义底部View
#import "AddConsigneVC.h" // 新建收货联系人

@interface ConsigneeListVC ()<UITableViewDelegate,UITableViewDataSource> {
    
    NSMutableArray *dataArr;
    BOOL   isMJRefresh;
}

@property (nonatomic, strong) UITableView *tableView;
/**
 *  底部的 新建联系人
 */
@property (nonatomic, strong) AddConsigneeView *addConsigneeView;
@property (nonatomic, strong) NSMutableDictionary *delePost;

@end

@implementation ConsigneeListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupViews];
    
   
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setupDatas];
}

#pragma mark 数据初始化
- (void)setupDatas {
//     dataArr = @[@{@"id":@"123",@"username":@"李淼秒",@"tel":@"18858587895"},@{@"id":@"123",@"username":@"李淼秒",@"tel":@"18858587895"},@{@"id":@"123",@"username":@"李淼秒",@"tel":@"18858587895"},@{@"id":@"123",@"username":@"李淼秒",@"tel":@"18858587895"}].mutableCopy;
    dataArr = [[NSMutableArray alloc]init];
    [self getMyConsignees];
}

#pragma mark 视图初始化
- (void)setupViews {
    
    self.navColor = SYSTEM_COLOR;
    
    self.labnav.textColor = [UIColor whiteColor];
    self.labnav.text = [UtilCheck language:@"setting.consignee"];
    self.labnav.backgroundColor = [UIColor clearColor];
    
    self.mBackColor = [UtilCheck hexStringToColor:@"f6f7fb" alpha:1];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 50) style:(UITableViewStyleGrouped)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[ConsigneeListCell class] forCellReuseIdentifier:@"consigneeListCell"];
    [self.view addSubview:self.tableView];
    
    self.addConsigneeView = [[AddConsigneeView alloc] initWithFrame:CGRectMake(0, self.view.bottom - 50 - 64, SCREEN_WIDTH, 50)];
    self.addConsigneeView.backgroundColor = [UIColor whiteColor];
    __weak typeof(self) weakSelf = self;
#pragma mark 新建收货联系人
    self.addConsigneeView.addConsigneeBlock = ^(){
        AddConsigneVC *vc = [[AddConsigneVC alloc] init];
        vc.isAddConsigne = YES;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };

    [self.view addSubview:self.addConsigneeView];
    
    isMJRefresh = YES;
    [self addHeader];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark- TalbleView Delegate&DataSource
#pragma mark-
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ConsigneeListCell * cell = [[ConsigneeListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"consigneeListCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
   [cell setDataDic:dataArr[indexPath.section]];
   
    cell.editBlock = ^(){
        
        if([UtilCheck DataIsNuLL:[NSString stringWithFormat:@"%@", [dataArr[indexPath.section] objectForKey:@"id"]]]) {
            // 收货联系人ID为空,不能修改
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"setting.cogeUpdateLimit"]];
            return;
        }
        
        AddConsigneVC *vc = [[AddConsigneVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        vc.isAddConsigne = NO;
        vc.consigneDic = dataArr[indexPath.section];
      
    };
    
    cell.delBlcok = ^(){
        
        
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"更新" message:@"确定删除该联系人吗？" preferredStyle:(UIAlertControllerStyleAlert)];
        
        UIAlertAction *logoutAction = [UIAlertAction actionWithTitle:[UtilCheck language:@"button.cancel"] style:(UIAlertActionStyleCancel) handler:nil];
        
        UIAlertAction *updateAction = [UIAlertAction actionWithTitle:[UtilCheck language:@"button.done"] style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            self.delePost = [NSMutableDictionary dictionary];
            [self.delePost setObject:[dataArr[indexPath.section] objectForKey:@"id"] forKey:@"id"];
            [dataArr removeObjectAtIndex:indexPath.section];
            
            [self deleteConsignee];
            [self.tableView reloadData];

        }];
        [alertC addAction:logoutAction];
        [alertC addAction:updateAction];
        [self presentViewController:alertC animated:YES completion:nil];

        
    };
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10.f;
}


#pragma mark- 网络请求
#pragma mark-

#pragma mark 获取收货联系人列表
- (void)getMyConsignees {
    
    [AFHttpTool postJsonDatawithUrl:@"myConsignees"  parameters:nil success:^(id responseObject) {
        
        isMJRefresh = YES;
        [self.tableView.header endRefreshing];

        if(1 == [[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue]) {
            
           
            if([[responseObject objectForKey:@"data"] isKindOfClass:[NSArray class]]){
                
                dataArr = nil;
                dataArr = [NSMutableArray arrayWithArray:[responseObject objectForKey:@"data"]];
                [self.tableView reloadData];
            }
        }
        else {
            //返回数据出问题 弹出服务器返回信息
            if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
            }
        }
        
    } fail:^(id responseObject, NSError *error) {
        
        isMJRefresh = YES;
        [self.tableView.header endRefreshing];

        [[BDHUD sharedManager] dismissHUD];
        
        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
        }else {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
        }
        
    }];
    
}

#pragma mark 删除联系人列表
- (void)deleteConsignee {
    
    [[BDHUD sharedManager] showBDHUD:self.view title:nil];
    [AFHttpTool postJsonDatawithUrl:@"deleteConsignee" parameters:self.delePost success:^(id responseObject) {
        
        [[BDHUD sharedManager] dismissHUD];
        
        if(1 == [[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue]) {
            
            NSString *info = [[responseObject objectForKey:@"head"] objectForKey:@"info"];
            
            if ([UtilCheck DataIsNuLL:info]) {
                // 修改收货联系人成功
                info = [UtilCheck language:@"setting.cogeUpdate"];
            }
            [[BDHUD sharedManager] showWords:info];
        }
        else {
            //返回数据出问题 弹出服务器返回信息
            if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
            }
        }
        
    } fail:^(id responseObject, NSError *error) {
        
        [[BDHUD sharedManager] dismissHUD];
        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
        }else {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
        }
        
    }];
}

#pragma mark- 其他事件
#pragma mark-

/**
 *  下拉刷新
 */
- (void)addHeader
{
    
    if(self.tableView.header==nil){
        __weak typeof(self) weakSelf = self;
        // 添加上拉刷新头部控件
        self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            if (isMJRefresh) {
                isMJRefresh = NO;
               [weakSelf getMyConsignees];
            }
            
        }];
        // 马上进入刷新状态
        [self.tableView.header beginRefreshing];
    }
}

@end
